package com.yamaha.bikemarket;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class BikeDetailFragment extends AMyActivity implements
		OnItemClickListener {

	private ImageLoader imageLoader;
	ViewGroup container;
	private LayoutInflater inflater;

	private JSONObject item = null;

	final List<String> list = new ArrayList<String>();
	private final Map<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();

	private SimpleFacebook simpleFacebook;

	public BikeDetailFragment() {
		super(MenuType.NONE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bike_detail_layout);

		simpleFacebook = SimpleFacebook.getInstance(this);

		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

		final String detail = getIntent().getStringExtra("item");
		try {
			item = new JSONObject(detail);
		} catch (JSONException e) {
			LogUtil.e("BikeDetailFragment", e.getMessage(), e);

			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
			finish();
			return;
		}

		final DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory().cacheOnDisc().build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(
				defaultOptions).build();
		if (null != imageLoader && imageLoader.isInited()) {
			imageLoader.destroy();
			imageLoader = null;
		}
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			imageLoader.init(config);
		}

		final Button mailButton = (Button) findViewById(R.id.mail_button);
		final Button shareButton = (Button) findViewById(R.id.share_button);
		final Button favButton = (Button) findViewById(R.id.fav_button);
		final Button commentButton = (Button) findViewById(R.id.comment_button);
		final Button phoneButton = (Button) findViewById(R.id.call_button);
		final Gallery gallery = (Gallery) findViewById(R.id.gallery1);
		final Button doneButton = (Button) findViewById(R.id.done_button);

		mailButton.setOnClickListener(this);
		shareButton.setOnClickListener(this);
		favButton.setOnClickListener(this);
		commentButton.setOnClickListener(this);
		phoneButton.setOnClickListener(this);
		gallery.setOnItemClickListener(this);
		doneButton.setOnClickListener(this);

		setListenerForMenu();

		changeBottomLayout();
	}

	private void changeBottomLayout() {
		final ImageView menuBottomBar = (ImageView) findViewById(R.id.menu_bottom_bar);
		final Button favButton = (Button) findViewById(R.id.fav_button);

		try {
			final String posterId = item.getString("user_id");

			if (SCStaticFunc.getUserId(this).equals(posterId)) {
				menuBottomBar.setImageResource(R.drawable.detail_bottom_my);
				favButton.setEnabled(false);
			} else {
				final boolean isFav = item.getBoolean("is_fav");
				if (isFav) {
					menuBottomBar
							.setImageResource(R.drawable.detail_bottom_remove);
				} else {
					menuBottomBar.setImageResource(R.drawable.detail_bottom_2x);
				}
			}
		} catch (JSONException e) {
			LogUtil.e("BikeDetailFragment", "Error : " + e.getMessage(), e);
		}
	}

	@Override
	protected List<EditText> getEditTexts() {
		return null;
	}

	@Override
	public void onClick(View v) {
		if (onMenuClick(v)) {
			return;
		}

		switch (v.getId()) {
		case R.id.mail_button: {

			try {

				final String title = "Bike Market";
				final StringBuilder description = new StringBuilder();
				description.append("Brand : " + item.getString("brand_name")
						+ "\n");
				description.append("Model : " + item.getString("model_name")
						+ "\n");
				description.append("Reg Year : " + item.getInt("reg_year")
						+ "\n");
				description.append("Color : " + item.getString("color_name")
						+ "\n");
				description.append("Price : " + item.getString("price")
						+ " บาท" + "\n");
				description.append("Description : " + "\n");
				description.append(item.getString("description"));

				final String email = item.getString("email");

				Uri uri = null;
				final Set<String> keySet = bitmaps.keySet();
				if (null != keySet && keySet.size() > 0) {
					final Bitmap bitmap = bitmaps.get(keySet.iterator().next());
					File mFile = savebitmap(bitmap);
					uri = Uri.fromFile(mFile);
				}

				sendMail(title, description.toString(), uri, email);
			} catch (JSONException e) {
				LogUtil.e("BikeDetailFragment",
						"Send Mail : " + e.getMessage(), e);
			}
		}
			break;
		case R.id.call_button: {
			handleCallPhone();
		}
			break;
		case R.id.share_button: {
			handleShare();
		}
			break;
		case R.id.done_button: {
			handleDone();
		}
			break;
		case R.id.comment_button: {
			handleComment();
		}
			break;
		case R.id.fav_button: {
			handleFav();
		}
			break;
		}

	}

	private void handleComment() {
		final Intent intent = new Intent(this, CommentFragment.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		intent.putExtra("detail", item.toString());
		startActivity(intent);
	}

	private void handleDone() {
		final RelativeLayout fullScreenLayout = (RelativeLayout) findViewById(R.id.full_screen_view);
		fullScreenLayout.setVisibility(View.GONE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		simpleFacebook.onActivityResult(this, requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void handleShare() {

		simpleFacebook.login(new OnLoginListener() {

			@Override
			public void onFail(String reason) {
				LogUtil.w("BikeDetailFragment", "Facebook onFail " + reason);
			}

			@Override
			public void onException(Throwable throwable) {
				LogUtil.e("BikeDetailFragment", "Facebook onException "
						+ throwable.getMessage(), throwable);
			}

			@Override
			public void onThinking() {
				LogUtil.i("BikeDetailFragment", "Facebook onThinking");
			}

			@Override
			public void onNotAcceptingPermissions() {
				LogUtil.w("BikeDetailFragment",
						"Facebook onNotAcceptingPermissions");
			}

			@Override
			public void onLogin() {
				LogUtil.i("BikeDetailFragment", "Facebook onLogin");
				doShare();
			}
		});
	}

	private void doShare() {

		try {
			final StringBuilder description = new StringBuilder();
			description
					.append("Brand : " + item.getString("brand_name") + "\n");
			description
					.append("Model : " + item.getString("model_name") + "\n");
			description.append("Reg Year : " + item.getInt("reg_year") + "\n");
			description
					.append("Color : " + item.getString("color_name") + "\n");
			description.append("Price : " + item.getString("price") + " บาท"
					+ "\n");
			description.append("Description : " + "\n");
			description.append(item.getString("description"));

			String picture = "";
			if (list.size() > 0) {
				picture = list.get(0);
			}

			final Bundle params = new Bundle();
			params.putString("name", getResources()
					.getString(R.string.app_name));
			params.putString("caption", "");
			params.putString("description", description.toString());
			params.putString("link", "");
			params.putString("picture", picture);

			final WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this,
					SimpleFacebook.getOpenSession(), params))
					.setOnCompleteListener(new OnCompleteListener() {

						@Override
						public void onComplete(Bundle values,
								FacebookException error) {
							if (error == null) {
								// When the story is posted, echo the success
								// and the post Id.
								final String postId = values
										.getString("post_id");
								if (postId != null) {
									LogUtil.i("BikeDetailFragment",
											"Post Success : " + postId);
									Toast.makeText(BikeDetailFragment.this,
											"Post Success", Toast.LENGTH_SHORT)
											.show();
								} else {
									// User clicked the Cancel button
									LogUtil.i("BikeDetailFragment",
											"User click Cancel.");
									Toast.makeText(BikeDetailFragment.this,
											"Publish cancelled",
											Toast.LENGTH_SHORT).show();
								}
							} else if (error instanceof FacebookOperationCanceledException) {
								// User clicked the "x" button
								LogUtil.i("BikeDetailFragment",
										"User click Cancel.");
								Toast.makeText(BikeDetailFragment.this,
										"Publish cancelled", Toast.LENGTH_SHORT)
										.show();
							} else {
								// Generic, ex: network error
								LogUtil.e(
										"BikeDetailFragment",
										"Facebook Share Error : "
												+ error.getLocalizedMessage(),
										error);
								Toast.makeText(BikeDetailFragment.this,
										"Error posting story",
										Toast.LENGTH_SHORT).show();
							}
						}

					}).build();
			feedDialog.show();
		} catch (JSONException e) {
			LogUtil.e("BikeDetailFragment", "Error : " + e.getMessage(), e);
		}
	}

	private File savebitmap(Bitmap bmp) {
		final String extStorageDirectory = Environment
				.getExternalStorageDirectory().toString();
		OutputStream outStream = null;

		File file = new File(extStorageDirectory, "Email.png");
		if (file.exists()) {
			file.delete();
			file = new File(extStorageDirectory, "Email.png");
		}

		try {
			outStream = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e("BikeDetailFragment", "Save Bitmap " + e.getMessage(), e);
			return null;
		}
		return file;
	}

	@Override
	protected void onResume() {
		super.onResume();

		final TextView userDetailText = (TextView) findViewById(R.id.user_detail);
		final TextView modelDetailText = (TextView) findViewById(R.id.model_detail);
		final TextView brandDetailText = (TextView) findViewById(R.id.brand_detail);
		final TextView priceDetailText = (TextView) findViewById(R.id.price_detail);
		final TextView engineText = (TextView) findViewById(R.id.engine_detail);
		final TextView dateDetailText = (TextView) findViewById(R.id.date_detail);
		final TextView timeText = (TextView) findViewById(R.id.time_detail);
		final TextView description = (TextView) findViewById(R.id.description_text);
		final TextView code = (TextView) findViewById(R.id.code_detail);
		final TextView color = (TextView) findViewById(R.id.color_detail);

		try {
			// Check User Id
			final String userId = item.getString("user_id");

			final ImageView menuBottom = (ImageView) findViewById(R.id.menu_bottom_bar);
			if (SCStaticFunc.getUserId(this).equals(userId)) {
				menuBottom.setImageResource(R.drawable.detail_bottom_my);
			} else {
				final boolean is_fav = item.getBoolean("is_fav");
				if (is_fav) {
					menuBottom
							.setImageResource(R.drawable.detail_bottom_remove);
				} else {
					menuBottom.setImageResource(R.drawable.detail_bottom_2x);
				}
			}

			final long updateTime = item.getLong("update_time");
			final java.util.Date time = new java.util.Date(updateTime * 1000);

			final SimpleDateFormat dateFormat = new SimpleDateFormat(
					"dd/MM/yyyy", Locale.US);
			final SimpleDateFormat timeFormat = new SimpleDateFormat(
					"HH:mm:ss", Locale.US);

			modelDetailText.setText("Model : " + item.getString("model_name"));
			brandDetailText.setText("Brand : " + item.getString("brand_name"));
			priceDetailText.setText("Price : " + item.getString("price"));
			engineText.setText("Reg Year : " + item.getString("reg_year"));
			userDetailText.setText("User : " + item.getString("user_name"));
			color.setText("Color : " + item.getString("color_name"));
			dateDetailText.setText(dateFormat.format(time));
			timeText.setText(timeFormat.format(time));
			description.setText(item.getString("description"));
			code.setText("Code : " + item.getString("code"));

			list.clear();
			bitmaps.clear();
			final JSONArray pix = item.getJSONArray("pix");
			if (pix != null) {
				for (int i = 0; i < pix.length(); i++) {
					list.add(pix.getString(i));
				}
			}

			final Gallery gallery = (Gallery) findViewById(R.id.gallery1);
			final MyAdapter myAdapter = new MyAdapter();
			gallery.setAdapter(myAdapter);

		} catch (JSONException e) {
			e.printStackTrace();
			LogUtil.e("BikeDetailFragment", e.getMessage(), e);
		}
	}

	private class ItemHolder {
		ImageView imageView;
	}

	private class MyAdapter extends BaseAdapter implements OnClickListener {

		public MyAdapter() {
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup container) {

			final ItemHolder holder;
			if (convertView == null) {
				holder = new ItemHolder();

				holder.imageView = new ImageView(BikeDetailFragment.this);
				holder.imageView.setLayoutParams(new Gallery.LayoutParams(500,
						320));
				convertView = holder.imageView;

				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			holder.imageView.setId(0x55555);
			holder.imageView.setTag(position);
			holder.imageView.setScaleType(ScaleType.CENTER_INSIDE);
			holder.imageView.setPadding(25, 5, 25, 5);
			holder.imageView.setImageResource(R.drawable.pix_add);
			// holder.imageView.setOnClickListener(this);
			imageLoader.displayImage(list.get(position), holder.imageView,
					new ImageLoadingListener() {

						@Override
						public void onLoadingStarted(String imageUri, View view) {
							LogUtil.i("BikeDetailFragment",
									"Load Image Started : " + imageUri);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							LogUtil.w("BikeDetailFragment",
									"Load Image Failed : " + imageUri);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							bitmaps.put(imageUri, loadedImage);
						}

						@Override
						public void onLoadingCancelled(String imageUri,
								View view) {
							// TODO Auto-generated method stub

						}
					});

			return convertView;
		}

		@Override
		public void onClick(View v) {
			final int position = (Integer) v.getTag();
			final String url = list.get(position);

			if (url != null && url.length() > 0) {
				final RelativeLayout fullScreenLayout = (RelativeLayout) findViewById(R.id.full_screen_view);
				fullScreenLayout.setVisibility(View.VISIBLE);

				final ImageView image = (ImageView) findViewById(R.id.imageView1);
				imageLoader.displayImage(url, image);
			}
		}
	}

	private void sendMail(final String title, final String description,
			final Uri attachment, final String email) {

		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
		i.putExtra(Intent.EXTRA_SUBJECT, title);
		i.putExtra(Intent.EXTRA_TEXT, description);
		if (attachment != null) {
			i.putExtra(Intent.EXTRA_STREAM, attachment);
		}
		try {
			startActivity(Intent.createChooser(i, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(this, "There are no email clients installed.",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void handleFav() {
		try {

			final AsyncHttpClient client = new AsyncHttpClient();
			final RequestParams params = new RequestParams();
			params.put("id", item.getString("temp"));
			params.put("user_id", SCStaticFunc.getUserId(this));

			client.post(API.BOOKING, params, new MyAsyncHttpResponseHandler(
					API.BOOKING, this) {

				@Override
				public void onStart() {
					super.onStart();

					Utils.showProgressDialog(BikeDetailFragment.this, "",
							"Please wait..");
				}

				@Override
				public void onSuccess(final String res) {
					super.onSuccess(res);

					try {
						final JSONObject resObj = new JSONObject(res);
						final JSONObject object = resObj
								.getJSONObject("message");
						final String code = object.getString("code");

						boolean isDealer = false;
						try {
							isDealer = item.getBoolean("is_dealer");
						} catch (JSONException e) {
							LogUtil.e(BikeDetailFragment.this.getClass()
									.getSimpleName(), e.getMessage(), e);
						}
						final boolean isDeleted = object.getBoolean("deleted");

						final ImageView menuBottom = (ImageView) findViewById(R.id.menu_bottom_bar);
						final String msg = (isDeleted) ? "Deleted" : "Added";

						if (isDeleted) {
							final TextView codeInDetail = (TextView) findViewById(R.id.code_detail);
							codeInDetail.setText("Code : " + code);

							menuBottom
									.setImageResource(R.drawable.detail_bottom_2x);
						} else {

							if (isDealer) {
								final AlertDialog.Builder builder = new AlertDialog.Builder(
										BikeDetailFragment.this);
								final View view = inflater.inflate(
										R.layout.code_layout, container, false);
								final TextView codeView = (TextView) view
										.findViewById(R.id.code_text);
								codeView.setText(code);
								// builder.setView(view);
								builder.setMessage(code);
								builder.setPositiveButton("Close",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();

												menuBottom
														.setImageResource(R.drawable.detail_bottom_remove);
											}
										});
								builder.create().show();
							}

							final TextView codeInDetail = (TextView) findViewById(R.id.code_detail);
							codeInDetail.setText("Code : " + code);

							menuBottom
									.setImageResource(R.drawable.detail_bottom_remove);

						}

					} catch (JSONException e) {
						LogUtil.e("BikeDetailFragment",
								"Error : " + e.getMessage(), e);
					}
				}

				@Override
				public void onFinish() {
					super.onFinish();
					Utils.closeAllDialog();
				}
			});
		} catch (JSONException e) {
			LogUtil.e("BikeDetailFragment", "Error : " + e.getMessage(), e);
		}
	}

	//
	// @Override
	// public void onSuccess(String res) {
	// Log.v("Fav Success", res);
	//
	// // Check Is Dealer
	// try {
	// final JSONObject resObj = new JSONObject(res);
	// final JSONObject object = resObj
	// .getJSONObject("message");
	//
	// final String code = object.getString("code");
	//
	// final boolean isDealer = item.getBoolean("is_dealer");
	// final boolean isDeleted = object.getBoolean("deleted");
	//
	// final ImageView menuBottom = (ImageView) view
	// .findViewById(R.id.menu_bottom_bar);
	// final String msg = (isDeleted) ? "Deleted" : "Added";
	// if (isDealer) {
	// if (!isDeleted) {
	//
	// final TextView codeInDetail = (TextView) view
	// .findViewById(R.id.code_detail);
	// codeInDetail.setText("Code : " + code);
	//
	// final AlertDialog.Builder builder = new AlertDialog.Builder(
	// getActivity());
	// final View view = inflater.inflate(
	// R.layout.code_layout, container, false);
	// final TextView codeView = (TextView) view
	// .findViewById(R.id.code_text);
	// codeView.setText(code);
	// // builder.setView(view);
	// builder.setMessage(code);
	// builder.setPositiveButton("Close",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(
	// DialogInterface dialog,
	// int which) {
	// dialog.dismiss();
	//
	// menuBottom
	// .setImageResource(R.drawable.detail_bottom_remove);
	// }
	// });
	// builder.create().show();
	// } else {
	//
	// final TextView codeInDetail = (TextView) view
	// .findViewById(R.id.code_detail);
	// codeInDetail.setText("Code : ");
	//
	// AlertDialogManager manager = new AlertDialogManager();
	// manager.showAlertDialog(getActivity(), "", msg,
	// false);
	//
	// menuBottom
	// .setImageResource(R.drawable.detail_bottom_2x);
	// }
	//
	// } else {
	// AlertDialogManager manager = new AlertDialogManager();
	// manager.showAlertDialog(getActivity(), "", msg,
	// false);
	// }
	//
	// } catch (JSONException e) {
	// Log.e("onSuccess After Fav", e.getMessage(), e);
	// }
	//
	// }
	//
	// @Override
	// public void onFailure(Throwable e, String error) {
	// Log.e("Fav Error", error, e);
	// }
	//
	// @Override
	// public void onFinish() {
	// cDialog.dismiss();
	// }
	// });
	// } catch (JSONException e) {
	// Log.e("handleFav", e.getMessage(), e);
	// }
	// }
	//
	private void handleCallPhone() {
		try {
			final String phone = item.getString("phone");

			if (null != phone && phone.length() > 0) {
				String uri = "tel:" + phone.trim();
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse(uri));
				startActivity(intent);
			}
		} catch (JSONException e) {
			LogUtil.e("BikeDetailFragment", "Call Phone : " + e.getMessage(), e);
		}
	}

	//
	// public static void requestPublishPermissions(Activity activity,
	// Session session, List<String> permissions, int requestCode) {
	// if (session != null) {
	// Session.NewPermissionsRequest reauthRequest = new
	// Session.NewPermissionsRequest(
	// activity, permissions).setRequestCode(requestCode);
	// session.requestNewPublishPermissions(reauthRequest);
	// }
	// }
	//
	// protected void onSessionStateChange(final Session session,
	// SessionState state, Exception exception) {
	// if (session != null && session.isOpened()) {
	// if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
	// // Session updated with new permissions
	// // so try publishing once more.
	// tokenUpdated();
	// }
	// }
	// }
	//
	// /**
	// * Called when additional permission request is copmleted successfuly.
	// */
	// private void tokenUpdated() {
	// // Check if a publish action is in progress
	// // awaiting a successful reauthorization
	// if (pendingAnnounce) {
	// // Publish the action
	// handleAnnounce();
	// }
	// }
	//
	// @Override
	// public void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// super.onActivityResult(requestCode, resultCode, data);
	// switch (requestCode) {
	// case REAUTH_ACTIVITY_CODE:
	// Session session = Session.getActiveSession();
	// if (session != null) {
	// session.onActivityResult(getActivity(), requestCode,
	// resultCode, data);
	// }
	// break;
	// }
	// }
	//
	// private void handleComment() {
	//
	// final AlertDialog.Builder builder = new AlertDialog.Builder(
	// getActivity());
	//
	// final EditText editText = new EditText(getActivity());
	// editText.setHeight(300);
	// editText.setGravity(Gravity.LEFT | Gravity.TOP);
	// builder.setView(editText);
	// builder.setTitle("Comment");
	// builder.setPositiveButton("Comment",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// sendComment(editText, dialog);
	// }
	// });
	// builder.setNegativeButton("Close",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// }
	// });
	// final AlertDialog dialog = builder.create();
	// dialog.show();
	//
	// final InputMethodManager imm = (InputMethodManager) getActivity()
	// .getSystemService(Context.INPUT_METHOD_SERVICE);
	// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
	//
	// }
	//
	// private void sendComment(final EditText editText,
	// final DialogInterface dialog) {
	//
	// final String comment = editText.getText().toString().trim();
	//
	// if (comment.length() > 0) {
	//
	// final InputMethodManager imm = (InputMethodManager) getActivity()
	// .getSystemService(Context.INPUT_METHOD_SERVICE);
	// imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	//
	// try {
	// final JSONObject item = SCStaticFunc.getData();
	//
	// final String item_id = item.getString("temp");
	// final String sub_type = item.getString("type");
	//
	// final RequestParams params = new RequestParams();
	// params.put("comment", comment);
	// params.put("item_id", item_id);
	// params.put("user_id", SCStaticFunc.getUserId());
	// params.put("sub_type", sub_type);
	//
	// client.post(API.COMMENT, params,
	// new AsyncHttpResponseHandler() {
	//
	// private ProgressDialog cDialog;
	//
	// @Override
	// public void onStart() {
	// cDialog = ProgressDialog.show(getActivity(),
	// "", "Sending Comment...");
	// }
	//
	// @Override
	// public void onSuccess(String res) {
	// Log.v("Comment Success", res);
	// }
	//
	// @Override
	// public void onFailure(Throwable e, String error) {
	// Log.e("Comment Error", error, e);
	// }
	//
	// @Override
	// public void onFinish() {
	// cDialog.dismiss();
	// dialog.dismiss();
	// }
	// });
	// } catch (JSONException e) {
	// Log.e("Comment Exception", e.getMessage(), e);
	// }
	//
	// } else {
	//
	// dialog.dismiss();
	// }
	// }
	//
	// private void handleAnnounce() {
	// pendingAnnounce = false;
	// Session session = Session.getActiveSession();
	//
	// final List<String> PERMISSIONS = Arrays.asList(new String[] {
	// "publish_actions", "publish_stream" });
	//
	// if (session == null || !session.isOpened()) {
	// return;
	// }
	//
	// List<String> permissions = session.getPermissions();
	// if (!permissions.containsAll(PERMISSIONS)) {
	// pendingAnnounce = true; // Mark that we are currently waiting for
	// // confirmation of publish permissions
	// session.addCallback(new Session.StatusCallback() {
	// @Override
	// public void call(final Session session,
	// final SessionState state, final Exception exception) {
	// onSessionStateChange(session, state, exception);
	// }
	// });
	// requestPublishPermissions(getActivity(), session, PERMISSIONS,
	// REAUTH_ACTIVITY_CODE);
	// return;
	// }
	//
	// // TODO: Publish the post. You would need to implement this method to
	// // actually post something
	// publishFeedDialog();
	// }
	//
	// private void publishFeedDialog() {
	//
	// if (Session.getActiveSession().isOpened()) {
	//
	// try {
	// final JSONObject item = SCStaticFunc.getData();
	//
	// final String title = item.getString("user_name");
	// final String brand = item.getString("brand_name");
	// final String model = item.getString("model_name");
	// final String color = item.getString("color_name");
	// final String price = item.getString("price");
	// final String desc = item.getString("description");
	//
	// final String descToShare = String
	// .format("Brand : %s\nModel : %s\nColor : %s\nPrice : %sบาท\nDescription : %s",
	// brand, model, color, price, desc);
	//
	// final JSONArray arrImage = item.getJSONArray("pix");
	// final String firstImg;
	// if (arrImage != null && arrImage.length() > 0) {
	// firstImg = arrImage.getString(0);
	// } else {
	// firstImg = "";
	// }
	//
	// Bundle params = new Bundle();
	// params.putString("name", title);
	// params.putString("caption", "Yamaha Motor Thailand");
	// params.putString("description", descToShare);
	// params.putString("picture", firstImg);
	//
	// WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
	// getActivity(), Session.getActiveSession(), params))
	// .setOnCompleteListener(new OnCompleteListener() {
	//
	// @Override
	// public void onComplete(Bundle values,
	// FacebookException error) {
	// if (error == null) {
	// // When the story is posted, echo the
	// // success
	// // and the post Id.
	// final String postId = values
	// .getString("post_id");
	// if (postId != null) {
	// Toast.makeText(
	// getActivity(),
	// // "Posted story, id: " +
	// // postId,
	// "Posted story",
	// Toast.LENGTH_SHORT).show();
	// } else {
	// // User clicked the Cancel button
	// Toast.makeText(
	// getActivity()
	// .getApplicationContext(),
	// "Publish cancelled",
	// Toast.LENGTH_SHORT).show();
	// }
	// } else if (error instanceof FacebookOperationCanceledException) {
	// // User clicked the "x" button
	// Toast.makeText(
	// getActivity()
	// .getApplicationContext(),
	// "Publish cancelled",
	// Toast.LENGTH_SHORT).show();
	// } else {
	// // Generic, ex: network error
	// Log.e("Facebook Error Post",
	// "Error Posting story", error);
	// Toast.makeText(
	// getActivity()
	// .getApplicationContext(),
	// "Facebook Error : "
	// + error.getMessage(),
	// Toast.LENGTH_SHORT).show();
	// }
	// }
	//
	// }).build();
	// feedDialog.show();
	// } catch (JSONException e) {
	// Log.e("Post JSON Error", e.getMessage(), e);
	// }
	// } else {
	// final AlertDialog.Builder builder = new AlertDialog.Builder(
	// getActivity());
	// builder.setTitle("Error");
	// builder.setMessage("Please close this app and re-login Facebook again.");
	// builder.setCancelable(false);
	// builder.setNegativeButton("Close App",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// getActivity().finish();
	// System.exit(0);
	// }
	// });
	// builder.create().show();
	// }
	// }

	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position,
			long id) {
		final String url = list.get(position);
		final RelativeLayout fullScreenLayout = (RelativeLayout) findViewById(R.id.full_screen_view);
		fullScreenLayout.setVisibility(View.VISIBLE);

		final ImageView image = (ImageView) findViewById(R.id.imageView1);
		imageLoader.displayImage(url, image);
	}
}
